// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router' // Vue 3 路由 API
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Welcome from '../views/Welcome.vue'
import Management from '../views/Management.vue'
import QueryTable from '../views/QueryTable.vue'
import ForgotPassword from '../views/ForgotPassword.vue'
import Profile from '../views/profile.vue'

// 路由规则不变
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/welcome',
    name: 'Welcome',
    component: Welcome,
    meta: { requiresAuth: true }
  },
  {
    path: '/management',
    name: 'Management',
    component: Management,
    meta: { requiresAuth: true }
  },
  {
    path: '/query',
    name: 'QueryTable',
    component: QueryTable,
    meta: { requiresAuth: true }
  },
  {
    path: '/forgot',
    name: 'ForgotPassword',
    component: ForgotPassword
  },
  {
    path: '/profile',
    name: 'profile',
    component: Profile,
    meta: { requiresAuth: true }
  }
]

// Vue 3 中创建路由实例的方式
const router = createRouter({
  history: createWebHistory(process.env.BASE_URL), // 替代 mode: 'history'
  routes
})

// 路由守卫逻辑不变（但需注意 Vue 3 中路由守卫的用法与 Vue 2 一致）
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  
  if (to.meta.requiresAuth) {
    if (!token) {
      next({ name: 'Login' });
    } else {
      try {
        if (token && token.trim() !== '') {
          next();
        } else {
          throw new Error('无效的 token');
        }
      } catch (error) {
        console.error('Token 验证出错:', error);
        localStorage.removeItem('token');
        next({ name: 'Login' });
      }
    }
  } else {
    next();
  }
  
  if (to.name === 'Login' && token) {
    next({ name: 'Welcome' });
  }
});

export default router